# -*- coding: utf-8 -*-
# @FileName : Upload.py
# @Time     : 2023/6/9 20:35
# @Author   : Zhong Runke

from flask import request, jsonify, g
from application import app, root_path, db
from web.controller.api import route_api
import os
from common.models.User import User
from common.libs.UrlManager import UrlManager


@route_api.route("/upload/avatar", methods=["POST"])
def uploadAvatar():
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    user_id = request.values.get("id")
    model_user = User.query.filter_by(id=user_id, status=1).first()
    if not model_user:
        resp['code'] = -1
        resp['msg'] = '数据库查询错误'
        return jsonify(resp)
    req = request.files
    file = req.get("imgfile")
    filename = file.filename
    folder_path = os.path.join(root_path + "/data/upload/")
    if not os.path.exists(folder_path):
        os.mkdir(folder_path)
    file_path = os.path.join(folder_path, filename)
    with open(file_path, 'wb') as f:
        f.write(file.read())

    model_user.avatar = filename
    db.session.add(model_user)
    db.session.commit()
    resp['data']['avatar_url'] = UrlManager.buildImageUrl(filename)
    return jsonify(resp)